export function generateAESKEY() {
  let d = new Date().getTime();
  let AESKey = "xxxxxxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    let r = (d + Math.random() * 16) % 16 | 0;
    d = Math.floor(d / 16);
    return (c == "x" ? r : (r & 0x3) | 0x8).toString(16);
  });
  return AESKey;
}

const CryptoJS = require("crypto-js");
//aes加密
export function aesEncrypt(data, secretKey) {
  const result = CryptoJS.AES.encrypt(
    data,
    CryptoJS.enc.Utf8.parse(secretKey),
    {
      iv: CryptoJS.enc.Utf8.parse("偏移量"),
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    }
  );
  return result.toString();
}

//aes解密
export function aesDecrypt(cipher, secretKey) {
  const decrypted = CryptoJS.AES.decrypt(
    cipher,
    CryptoJS.enc.Utf8.parse(secretKey),
    {
      iv: CryptoJS.enc.Utf8.parse("偏移量"),
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    }
  );
  return CryptoJS.enc.Utf8.stringify(decrypted);
}
export function translateArrayBufferToBase64(buffer){
    let binaryStr = "";
    const bytes = new Uint8Array(buffer);
    for(let i=0,len = bytes.byteLength;i<len;i++){
        binaryStr +=String.fromCharCode(bytes [i]);
    }
    return window.btoa(binaryStr );
}


export function translateBase64ToArrayBuffer(base64){
    const binaryStr = window.atob(base64);
    const byteLength = binaryStr.length;
    const bytes = new Uint8Array(byteLength);
    for(let i=0;i<byteLength;i++){
        bytes[i] = binaryStr.charCodeAt(i);
    }
    return bytes.buffer;
}
